// because this is done parallel we have to check and if FB.init is not done we have to do it before doLogin()
FBinitIsDone = false;
window.fbAsyncInit = function () {
    FB.init({
        appId: conf.FB_app_id,
        channelUrl: conf.FB_channel_url,
        status:true,
        cookie:true,
        xfbml:true
    });
    FBinitIsDone = true;
};

function doLogin(callBack) {
    if (!FBinitIsDone) {
        window.fbAsyncInit();
    }
    // this code is only for debugging!
    if (getURLParameter("uid")) {
        OurGame.UID = getURLParameter("uid");
        return;
    }
    // end
    FB.login(function (response) {
        if (response.authResponse) {
            FB.api('/me', function (response) {
                OurGame.UID = response.id;
                pusher = new Pusher(OurGame.appKey);
                pusher.connection.bind('connected', function () {
                    log("CONNECTED!");
                    OurGame.socketID = pusher.connection.socket_id;
                    if (callBack !== undefined) {
                        callBack();
                    }
                });
            });
        }
    },
    {
        perms:''
    }
    );
}

function getFBPictureUrlById(id) {
    if (id) {
        return 'https://graph.facebook.com/' + id + '/picture/?type=large';
    } else {
        return 'img/fb_profile_default.png';
    }
}

function getFBSquarePictureUrlById(id) {
    return 'https://graph.facebook.com/' + id + '/picture/?type=square';
}

function getFacebookNameById(id, callback, params) {
    FB.api('/' + id, function(response) {
        OurGame.playerName = response.name;
        if (callback !== undefined) {
            callback(response.name, params);
        }
    });
}

function FBFriendSelectorDialog(replaceableId) {
    // disable slider
    $('.sliderWrapper').fadeOut('fast');
    OurGame.doNotShowSlider = true;
    // choose friends
    var friendSelector, callbackSubmit;
    // When the user clicks OK, log a message
    callbackSubmit = function(selectedFriendIds) {
        friendId = selectedFriendIds[0];
        if (friendId) {
            log('Selected id: ' + friendId);
            OurGame.playerUIDs[replaceableId - 1] = friendId;
            log(OurGame.playerUIDs);
            replaceEmptySlotWithFriend(replaceableId, friendId);
            inviteFriend(friendId);
        }
        else {
            log('Friend selector did not return an id!');
        }
    };
    // Initialise the Friend Selector with options that will apply to all instances
    TDFriendSelector.init({debug: true});
    // Create some Friend Selector instances
    friendSelector = TDFriendSelector.newInstance({
        callbackMaxSelection     : 1,
        callbackSubmit           : callbackSubmit,
        maxSelection             : 1,
        friendsPerPage           : 5,
        autoDeselection          : true
    });
    friendSelector.showFriendSelector();
}

/**
 * Sends private message
 *
 * @param friendId can be an array [] of ids
 */
function inviteFriend(friendId) {
    if (isLocalhost()) {
        log(conf.gameMultiplayerUrl + OurGame.gameID);
    } else {
        FB.ui({
            app_id: conf.FB_app_id,
            method: 'send',
            name: conf.gameName,
            link: conf.gameMultiplayerUrl + OurGame.gameID,
            to: friendId,
            description: 'Press the link to play. Your friend is waiting for you!'
        });
    }
}

// Load the SDK Asynchronously
(function (d) {
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) {
        return;
    }
    js = d.createElement('script');
    js.id = id;
    js.async = true;
    js.src = "http://connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
}(document));